import Vue from 'vue'
import ToastComponent from '@/components/Toast.vue'

// 创建Toast构造器
const ToastConstructor = Vue.extend(ToastComponent)

// 创建Toast实例
let toastInstance = null

// 获取或创建Toast实例
function getToastInstance() {
  if (!toastInstance) {
    toastInstance = new ToastConstructor({
      el: document.createElement('div')
    })
    document.body.appendChild(toastInstance.$el)
  }
  return toastInstance
}

// Toast方法
const Toast = {
  // 显示成功消息
  success(message, options = {}) {
    const instance = getToastInstance()
    instance.addToast({
      type: 'success',
      message,
      title: options.title || '成功',
      duration: options.duration
    })
  },

  // 显示错误消息
  error(message, options = {}) {
    const instance = getToastInstance()
    instance.addToast({
      type: 'error',
      message,
      title: options.title || '错误',
      duration: options.duration
    })
  },

  // 显示警告消息
  warning(message, options = {}) {
    const instance = getToastInstance()
    instance.addToast({
      type: 'warning',
      message,
      title: options.title || '警告',
      duration: options.duration
    })
  },

  // 显示信息消息
  info(message, options = {}) {
    const instance = getToastInstance()
    instance.addToast({
      type: 'info',
      message,
      title: options.title || '提示',
      duration: options.duration
    })
  },

  // 通用显示方法
  show(options) {
    if (typeof options === 'string') {
      options = { message: options }
    }
    
    const instance = getToastInstance()
    instance.addToast({
      type: options.type || 'info',
      message: options.message,
      title: options.title,
      duration: options.duration
    })
  },

  // 清除所有Toast
  clear() {
    if (toastInstance) {
      toastInstance.toasts = []
      toastInstance.progressIntervals.forEach(interval => clearInterval(interval))
      toastInstance.progressIntervals.clear()
    }
  }
}

// Vue插件安装方法
const ToastPlugin = {
  install(Vue) {
    // 添加全局属性
    Vue.prototype.$toast = Toast
    
    // 添加全局方法
    Vue.toast = Toast
  }
}

export default ToastPlugin
export { Toast }